'use strict';

var path = require('path');
var fs = require('fs');
var Promise = require('bluebird');

var _ = require('lodash');
var glob = require('glob');
var request = require('request');

var expressConf = require('../../config/config');
var config = require('../../config/mockPathMap.json');
var mockDir = path.resolve(process.cwd(), 'app/mock/');
var vmDir = path.resolve(process.cwd(), 'app/views/');

module.exports.getMockData =  function(vmPath,name) {
    // console.log(vmPath,name,_.find(config,{path:vmPath}));
    var mockFiles = _.chain(glob.sync(mockDir + '/{,**/}*.json')).map(function (file) {
        return {fileName:path.basename(file,'.json'),path:file,pathName:_.replace(_.replace(file,mockDir + '/',''),/.json$/,'')};
    }).value();
    var pageArguments = _.transform(_.get(module.exports.getPageConf(),[name,'arguments']),function (result, n) {
        _.set(result,n,'');
    },{});
    if(_.find(config,{path:vmPath}) != undefined){
        //返回已经配置好的模拟数据
        return Promise.resolve(_.assign(pageArguments,JSON.parse(fs.readFileSync(path.join(mockDir,_.find(config,{path:vmPath}).data)).toString())));
    }else if(_.find(mockFiles,{pathName:vmPath}) != undefined){
        //自动找相对应路径的模拟数据
        return Promise.resolve(_.assign(pageArguments,JSON.parse(fs.readFileSync(_.find(mockFiles,{pathName:vmPath}).path).toString())));
    }else{
        return Promise.resolve(pageArguments);
        //请求相对应控制器的模拟数据
        // return module.exports.checkControllers(expressConf.ip + ':' + expressConf.port +'/' + vmPath).then(function (Controllers) {
        //     if(Controllers.status){
        //         return Promise.resolve(Controllers.body);
        //     }else{
        //         return Promise.resolve({});
        //     }
        // });
    }
};

module.exports.checkControllers = function (url) {
    return new Promise(function (resolve,reject) {
        request.post(url, function(err, res, body) {
                if(err) resolve({status:false,body:{}});
                resolve({status:res.statusCode == '200',body:body});
        });
    });
};

module.exports.getPageConf = function () {
    return _.transform(_.chain(glob.sync(vmDir + '/front/**/package.json')).map(function (confPath) {
        return _.result(JSON.parse(fs.readFileSync(confPath).toString()),'pages');
    }).thru(_.flattenDeep).value(),function (result, n) {
        result[n.name] = n;
    },{});
}